{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Watch a Deep Q-Network Agent! \n",
    "\n",
    "### 1.Start the Environment "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch version:  1.2.0\n",
      "input_dim:  8 , output_dim:  2\n"
     ]
    }
   ],
   "source": [
    "import gym\n",
    "import numpy as np\n",
    "import torch\n",
    "\n",
    "import ddpg_agent_1\n",
    "import ddpg_agent_2\n",
    "import time\n",
    "\n",
    "env = gym.make('LunarLanderContinuous-v2')\n",
    "\n",
    "print('torch version: ', torch.__version__)\n",
    "\n",
    "seed = 0\n",
    "env.seed(seed)\n",
    "torch.manual_seed(seed)\n",
    "np.random.seed(seed)\n",
    "\n",
    "state = env.reset()\n",
    "state_dim = env.observation_space.shape[0]\n",
    "action_dim = env.action_space.shape[0] \n",
    "\n",
    "print('input_dim: ', state_dim, ', output_dim: ', action_dim) \n",
    "\n",
    "agent1 = ddpg_agent_1.Agent(state_dim, action_dim, random_seed=8)        \n",
    "agent2 = ddpg_agent_2.Agent(state_dim, action_dim, random_seed=8)        \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Prepare Load"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load(agent, directory, filename):\n",
    "    agent.actor_local.load_state_dict(torch.load('%s/%s_actor_local.pth' % (directory,  filename)))\n",
    "    agent.actor_target.load_state_dict(torch.load('%s/%s_actor_target.pth' % (directory,  filename)))\n",
    "    agent.critic_local.load_state_dict(torch.load('%s/%s_critic_local.pth' % (directory,  filename)))\n",
    "    agent.critic_target.load_state_dict(torch.load('%s/%s_critic_target.pth' % (directory,  filename)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. Prepare Player"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import deque\n",
    "import os\n",
    "import numpy as np\n",
    "\n",
    "def play(env, agent, n_episodes):\n",
    "    \n",
    "    state = env.reset()\n",
    "    scores_deque = deque(maxlen=100)\n",
    "\n",
    "    for i_episode in range(1, n_episodes+1):\n",
    "        state = env.reset()\n",
    "        agent.reset()\n",
    "        \n",
    "        total_reward = 0\n",
    "        time_start = time.time()\n",
    "        timesteps =  0\n",
    "        \n",
    "        done = False\n",
    "\n",
    "        while True:\n",
    "            \n",
    "            action = agent.act(state, add_noise=False)\n",
    "            env.render()\n",
    "            next_state, reward, done, _ = env.step(action)\n",
    "            total_reward += reward\n",
    "            \n",
    "            #agent.step(state, action, reward, next_state, done, timesteps)\n",
    "            state = next_state\n",
    "            timesteps += 1\n",
    "            \n",
    "            if done:\n",
    "                break \n",
    "\n",
    "        delta = (int)(time.time() - time_start)\n",
    "        \n",
    "        scores_deque.append(total_reward)\n",
    "\n",
    "        print('Episode {}\\tAverage Score: {:.2f}, \\t Timesteps: {} \\tTime: {:02}:{:02}:{:02}'\\\n",
    "                  .format(i_episode, np.mean(scores_deque), timesteps,\\\n",
    "                          delta//3600, delta%3600//60, delta%60))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. Load and Play (LunarLanderContinuous-v2-DDPG_746 epis.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Episode 1\tAverage Score: 261.48, \t Timesteps: 363 \tTime: 00:00:12\n",
      "Episode 2\tAverage Score: 267.51, \t Timesteps: 336 \tTime: 00:00:05\n",
      "Episode 3\tAverage Score: 252.92, \t Timesteps: 287 \tTime: 00:00:04\n",
      "Episode 4\tAverage Score: 250.10, \t Timesteps: 321 \tTime: 00:00:05\n",
      "Episode 5\tAverage Score: 251.13, \t Timesteps: 275 \tTime: 00:00:04\n",
      "Episode 6\tAverage Score: 253.06, \t Timesteps: 283 \tTime: 00:00:04\n",
      "Episode 7\tAverage Score: 251.09, \t Timesteps: 314 \tTime: 00:00:05\n"
     ]
    }
   ],
   "source": [
    "load(agent1, 'dir_chk_1', 'LLC-v2')\n",
    "play(env=env, agent=agent1, n_episodes=7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5. Load and Play (LunarLanderContinuous-v2-DDPG_2560.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Episode 1\tAverage Score: 252.94, \t Timesteps: 347 \tTime: 00:00:05\n",
      "Episode 2\tAverage Score: 250.06, \t Timesteps: 202 \tTime: 00:00:03\n",
      "Episode 3\tAverage Score: 253.39, \t Timesteps: 261 \tTime: 00:00:04\n",
      "Episode 4\tAverage Score: 257.17, \t Timesteps: 261 \tTime: 00:00:04\n",
      "Episode 5\tAverage Score: 259.15, \t Timesteps: 219 \tTime: 00:00:03\n",
      "Episode 6\tAverage Score: 245.38, \t Timesteps: 382 \tTime: 00:00:06\n",
      "Episode 7\tAverage Score: 239.42, \t Timesteps: 246 \tTime: 00:00:04\n"
     ]
    }
   ],
   "source": [
    "load(agent2, 'dir_chk_2', 'LunarLanderContinuous-v2')\n",
    "play(env=env, agent=agent2, n_episodes=7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "env.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml2-kernel",
   "language": "python",
   "name": "ml2-kernel"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
